<?php

namespace App\Models;

use App\Enums\GoodsClassStatusEnum;
use App\Traits\ModelEventTrait;
use Illuminate\Database\Eloquent\SoftDeletes;

class GoodsClass extends BaseModel
{
    use ModelEventTrait;
    use SoftDeletes;

    const KEY = 'id';
    const TABLE = 'sp_goods_class';

    protected $table = self::TABLE;
    protected $primaryKey = self::KEY;
    protected $connection = 'mysql';

    // public $timestamps = false;
    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';
    const DELETED_AT = 'delete_time';

    const goods_class_category = 'goods_class_category';//分类redis key


    protected $guarded = [];

    protected $appends = [
        'status_name',
        'imgurl_full',
    ];

    protected $hidden = [
        self::DELETED_AT,
    ];

    protected $casts = [
        'create_time' => 'datetime:Y-m-d H:i:s',
        'update_time' => 'datetime:Y-m-d H:i:s',
    ];

    public function getImgurlFullAttribute()
    {
        if (empty($this->image)) {
            return '';
        }
        return config('alipay.oss.imgHost') . $this->image;
    }
    public function getStatusNameAttribute()
    {
        return GoodsClassStatusEnum::getNameByKey($this->status);
    }

    public function getAll()
    {
        $data=(new static())->select('id','name','sort','status')
            ->where('pid',0)
            ->orderBy('sort','asc')
            ->orderBy('id','desc')->get();
        foreach ($data as $key => &$value){
            $data[$key]['children']=(new static())->select('id','name','sort','status')->where('pid',$value['id'])->get();
        }
        return $data;
    }
    public function getApiAll()
    {
        $data=(new static())->select('id','name','image','sort','status')
            ->where('status',GoodsClassStatusEnum::ON_SHELF()->getKey())
            ->where('pid',0)
            ->orderBy('sort','asc')
            ->orderBy('id','desc')->get();
        foreach ($data as $key => &$value){
            $data[$key]['children']=(new static())->select('id','name','image','sort','status')
                ->where('status',GoodsClassStatusEnum::ON_SHELF()->getKey())
                ->where('pid',$value['id'])
                ->orderBy('sort','asc')
                ->orderBy('id','desc')->get();
        }
        return $data;
    }
}
